import axios from 'axios';
import { Message } from 'element-ui';
import router from '../router';

import Webrtc2Sip from '@/utils/Webrtc2Sip';

axios.defaults.baseURL = '/idispatch';

axios.interceptors.request.use(
  config => {
    const tokenSign = sessionStorage.getItem('tokenSign');
    if (!config.login && tokenSign) config.headers.Authorization = tokenSign;
    return config;
  },
  error => {
    if (sessionStorage.getItem('tokenSign')) {
      return Promise.reject(error);
    }
  }
);

axios.interceptors.response.use(
  response => {
    if (
      response.data.msg === 'fail' &&
      (response.data.reason == 'user_logout' ||
        response.data.reason == 'The_user_is_not_login' ||
        response.data.reason == "'NoneType' object has no attribute 'operator'")
    ) {
      sessionStorage.clear();
      Webrtc2Sip.destroy();
      router.push('/login');
    } else if (
      (response.data.msg == 'fail' || response.data.reason == 'fail') &&
      sessionStorage.getItem('tokenSign')
    ) {
      Message.warning(response.data.reason);
    } else {
      return Promise.resolve(response);
    }
  },
  error => {
    if (error.request.status === 500) {
      // 连接服务器失败
      sessionStorage.clear();
      Webrtc2Sip.destroy();
      router.push('/login');
      return Promise.reject('连接服务器失败');
    }
    return Promise.reject(error);
  }
);

export default axios;
